""" World edit mode. """

from pygame.locals import *
import pygame

from pgEngine.point import Point, AxisAlignedBoundingBox

import editTools, editPalettes
from colors import *


class EditMode:
    def __init__(self, game, window):
        self.game = game
        self.window = window
        self.map = window.map
        self.screen = self.window.screen
        
        # Empty mask.
        self.selection = []
        self.selectionId = 0
        
        self.tilePalette = editPalettes.TilePalette(window, self)
        self.clipPalette = editPalettes.ClipboardPalette(window, self)
        self.toolBox = editTools.Toolbox(self)

        self.antStep = 0
        self.marchingAnts = []
        self.createMarchingAnts()

        
    def drawEditor(self):        
        self.map.draw(self.window.curT,
                      self.game.ocean,
                      self.window.mappos,
                      ("Tiles",))
    
    def drawMenu(self):
        # Draw the background.
        # Called by Toolbox.drawMenu.
        self.window.drawOverlay("editMenu", self.screen, "menu")
        #self.screen.blit(self.window.bgrEditMenu, self.window.rcMenu)
        return False
        
    
    def setTile(self, button, tileX, tileY, tileName):
        prevTile = self.game.ocean.tiles.get((tileX,tileY), "water")
        if button == 1 and prevTile != tileName:
            self.window.dialogMessage("Set (%i,%i) to %s." %
                              (tileX, tileY, tileName))
            self.game.ocean.setTile(tileX, tileY, tileName)
        elif button == 3 and prevTile != "water":
            self.window.dialogMessage("Reset (%i,%i) to water." %
                                      (tileX, tileY))
            self.game.ocean.setTile(tileX, tileY, "water")
        self.map.dirty = True

    
    def onEvent(self, event):
        retVal = None
        
        if event.type == MOUSEBUTTONDOWN:
            mousePos = event.pos
            if not self.window.checkOverlayClick(mousePos):
                pass
            
            elif event.button == 4:
                self.window.mappos.y += 4
                retVal = False
                
            elif event.button == 5:
                self.window.mappos.y -= 4
                retVal = False
                
            elif event.button == 6:
                self.window.mappos.x += 4
                retVal = False
                
            elif event.button == 7:
                self.window.mappos.x -= 4
                retVal = False
        
        elif event.type == KEYDOWN:
            
            if event.key == K_d and event.mod & KMOD_CTRL:
                self.selection[:] = []
                retVal = False

            elif event.key == K_c and event.mod & KMOD_CTRL:
                self.clipPalette.copy()
                retVal = False

            elif event.key == K_x and event.mod & KMOD_CTRL:
                self.clipPalette.cut()
                retVal = False

            elif event.key == K_v and event.mod & KMOD_CTRL:
                # Paste into floating selection
                self.clipPalette.put()
                retVal = False
        
        return retVal
        

    def onDrawMapObjects(self, surface):
        if self.game.state != self.game.STOPPED:
            self.game.stop()

    def createMarchingAnts(self):
        for n in range(8):
            maH = pygame.Surface((48,1))
            maV = pygame.Surface((1,48))
            maH.fill((255,255,255))
            maV.fill((255,255,255))
            for ant in range(n, 48, 6):
                pygame.draw.line(maH, black, (ant,0), (ant+2,0))
                pygame.draw.line(maV, black, (0,ant), (0,ant+2))
            self.marchingAnts.extend((maH, maV))
        

    def drawMarchingAnts(self, surface):
        wndMap = self.map

        if len(self.selection) > 0:
            self.antStep = (self.antStep + 1) % 18
            antIndex = self.antStep // 3
            if self.selection[2].y <= self.selection[3].y:
                pmin = Point(self.selection[2].x,
                            self.selection[3].y)
                pmax = Point(self.selection[3].x + 1,
                            self.selection[2].y - 1)
            else:
                pmin = self.selection[2]
                pmax = self.selection[3] + Point(1,-1)
            minX, minY = wndMap.getTilePos(pmin).pos
            maxX, maxY = wndMap.getTilePos(pmax).pos
            maH = self.marchingAnts[antIndex * 2]
            maV = self.marchingAnts[antIndex * 2 + 1]
            for col in range(minX, maxX, 48):
                surface.blit(maH, (col, minY))
                surface.blit(maH, (col, maxY))
            for row in range(minY, maxY, 48):
                surface.blit(maV, (minX, row))
                surface.blit(maV, (maxX, row))
        
    def drawFloatingSel(self, surface):
        # Get the current floater from the clipPalette
        item = self.clipPalette.getCurItem()
        # Skip it if we haven't copied anything yet.
        if (item is None or
            len(self.selection) < 4 or
            self.selectionId != self.clipPalette.selectionId):
            return

        box = AxisAlignedBoundingBox(*self.selection[2:4])
        scrPos = self.map.getTilePos(box.bottomleft)
        surface.blit(item.getFullSize(), scrPos.pos)

    def clearSelection(self):
        self.selection[:] = []
        self.selectionId += 1


